import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Vector;

import javax.xml.parsers.*;

import org.xml.sax.*;

/**
 *  Implements a simple minded utility for converting GPX files to flat ASCII.
 */
public class GpsReader extends org.xml.sax.helpers.DefaultHandler {

	PrintStream out = new PrintStream(new BufferedOutputStream(System.out));
	public Vector path = new Vector(100, 100);
	public Vector wayPts = new Vector(2, 10);
	String data; // data accumulator

	String time; // saved time value
	String name; // saved name value
	String ele; // saved elevation value
	String lat; // saved latitude value
	String lon; // saved longitude value
	int nPoints = 0;
	int nWayPoints = 0;
	
	public GpsReader(String fileName) {
		SAXParserFactory f = SAXParserFactory.newInstance();
//		GpsReader g = new GpsReader();
		try {
			f.newSAXParser().parse(fileName, this);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		out.flush(); // ensure that buffered output is flushed
	}
		
	/**
	 *  Called at the start of an XML element.
	 */
	public void startElement(String uri, String lname, String qname,
			Attributes atts) throws SAXException {

		data = "";
		if (qname.equals("trkpt") || qname.equals("rtept")
				|| qname.equals("wpt")) {
			time = name = ele = lat = lon = "-";
		} else if (qname.equals("rte") || qname.equals("trkseg")) {
			out.println();
		}
		if (atts != null) {
			for (int i = 0; i < atts.getLength(); i++) {
				String aname = atts.getQName(i);
				String value = atts.getValue(i);
				if (aname.equals("lat")) {
					lat = value;
				} else if (aname.equals("lon")) {
					lon = value;
				}
			}
		}
	}

	/**
	 *  Called at the end of an XML element.
	 */
	public void endElement(String uri, String sname, String qname)
			throws SAXException {

		if (qname.equals("wpt")) {
//			out.println();
			out.println("WPT \"" + name + "\" " + ele + " " + lat + " " + lon);
			nWayPoints++;
			double dlat = Double.parseDouble(lat);
			double dlon = Double.parseDouble(lon);
			double dele = Double.parseDouble(ele);
			wayPts.add(new Location(dlat, dlon, dele, time));
//			System.out.println("size: " + wayPts.size());
		} else if (qname.equals("trkpt")) {
			nPoints++;
			double dlat = Double.parseDouble(lat);
			double dlon = Double.parseDouble(lon);
			double dele = Double.parseDouble(ele);
			path.add(new Location(dlat, dlon, dele, time));
		} else if (qname.equals("rtept")) {
			out.println("RTE \"" + name + "\" " + ele + " " + lat + " " + lon);
		} else if (qname.equals("time")) {
			time = data;
		} else if (qname.equals("name")) {
			name = data;
		} else if (qname.equals("ele")) {
			ele = data;
		}
	}

	/**
	 *  Called to accumulate data belonging to an element.
	 */
	public void characters(char[] buf, int off, int len) throws SAXException {
		data += new String(buf, off, len);
	}

} // class GPXFlat
